﻿<%@ WebHandler Language="C#" Class="ZSTechNoticeReport" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Net;
using ReportBusiness;

/**
 * Description: 装配试车厂计通单报表
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan
 * Date:2022.11.24
 **/

public class ZSTechNoticeReport : IHttpHandler
{
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getData":
                        r = getData(jObject);//查询
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getDetail":
                        r = getDetail(jObject);//查询明细
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "exportExcel":
                        exportExcel(jObject);//导出
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    //查询方法
    Result getData(JObject jObject)
    {
        string sql = @"
SELECT tn.workflowname,tn.begindate,tn.finishdate,e.fullname,
       mfg.mfgordername,tn.engineno,CASE WHEN te.attributevalue IS NULL THEN '未分解' ELSE '已分解' END isplan,wf.workflowid,
       CASE WHEN te.attributevalue IS NULL AND SYSDATE <= tn.finishdate THEN '未执行'
            WHEN te.attributevalue IS NULL AND SYSDATE > tn.finishdate THEN '已超期'
            WHEN te.attributevalue IS NOT NULL AND wf.status = 2 THEN '已回收'
            WHEN te.attributevalue IS NOT NULL AND wf.status = 1 THEN '执行中' END status,te.containerid
FROM technicalnoticeinfo tn
LEFT JOIN employee e ON e.employeeid = tn.createemployeeid
LEFT JOIN 
(
     SELECT u.attributevalue,NVL(ep.containerid,ep.enginecontainerid) containerid
     FROM enginepartplan ep
     LEFT JOIN Userattribute u ON u.parentid = ep.mfgorderid AND u.userattributename='发动机'
     WHERE ep.type = 3
) te ON te.attributevalue = tn.engineno
LEFT JOIN
(
     SELECT u.attributevalue,mfg.mfgordername,mfg.mfgorderid
     FROM enginepartplan ep
     LEFT JOIN mfgorder mfg ON mfg.mfgorderid = ep.mfgorderid
     LEFT JOIN Userattribute u ON u.parentid = ep.mfgorderid AND u.userattributename='发动机'
     GROUP BY u.attributevalue,mfg.mfgordername,mfg.mfgorderid
) mfg ON mfg.attributevalue = tn.engineno
LEFT JOIN workflowbase wb ON wb.workflowname = tn.workflowname
LEFT JOIN workflow wf ON wf.workflowbaseid = wb.workflowbaseid                    
WHERE 1=1 
";
        //计通单号
        if (jObject["workflowname"] != null && jObject["workflowname"].ToString() != "")
        {
            sql += string.Format(" AND tn.workflowname LIKE '%{0}%' ", jObject["workflowname"].ToString());
        }

        //发动机号
        if (jObject["engineno"] != null && jObject["engineno"].ToString() != "")
        {
            sql += string.Format(" AND tn.engineno = '{0}' ", jObject["engineno"].ToString());
        }

        //订单号
        if (jObject["mfgordername"] != null && jObject["mfgordername"].ToString() != "")
        {
            sql += string.Format(" AND mfg.mfgordername = '{0}' ", jObject["mfgordername"].ToString());
        }

        //开始日期
        if (jObject["startdate"] != null && jObject["startdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["startdate"].ToString());
            if (arr.Count >= 2)
            {
                sql += string.Format(" AND tn.begindate >= to_date('{0}','yyyy-MM-dd')", arr[0].ToString());
                sql += string.Format(" AND tn.begindate <= to_date('{0}','yyyy-MM-dd')", arr[1].ToString());
            }
        }

        //结束日期
        if (jObject["enddate"] != null && jObject["enddate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["enddate"].ToString());
            if (arr.Count >= 2)
            {
                sql += string.Format(" AND tn.finishdate >= to_date('{0}','yyyy-MM-dd')", arr[0].ToString());
                sql += string.Format(" AND tn.finishdate <= to_date('{0}','yyyy-MM-dd')", arr[1].ToString());
            }
        }

        //编制人
        if (jObject["creater"] != null && jObject["creater"].ToString() != "")
        {
            sql += string.Format(" AND e.fullname LIKE '%{0}%' ", jObject["creater"].ToString());
        }

        //状态
        if (jObject["status"] != null && jObject["status"].ToString() != "")
        {
            string status = jObject["status"].ToString();
            if (status == "未执行")
            {
                sql += " AND te.attributevalue IS NULL AND SYSDATE <= tn.finishdate";
            }
            if (status == "执行中")
            {
                sql += " AND te.attributevalue IS NOT NULL AND wf.status = 1";
            }
            if (status == "已回收")
            {
                sql += " AND te.attributevalue IS NOT NULL AND wf.status = 2";
            }
            if (status == "已超期")
            {
                sql += " AND te.attributevalue IS NULL AND SYSDATE > tn.finishdate";
            }
        }
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //查询明细
    Result getDetail(JObject jObject)
    {
        string sql = @"
SELECT ws.workflowstepname,s.description,t.teamname,CASE WHEN csw.createdate IS NOT NULL THEN '已报工' ELSE '未报工' END isDone
FROM workflowstep ws
LEFT JOIN team t ON t.teamid = ws.teamid
LEFT JOIN stepinfo s ON s.workflowstepid = ws.workflowstepid
LEFT JOIN stepinfobase sb ON s.stepinfobaseid = sb.stepinfobaseid 
LEFT JOIN containerstepworkreport csw ON csw.isuse = 0 AND csw.containerid = '{0}' AND NVL(ws.workflowstepid,s.stepinfoid) = NVL(csw.workflowstepid,csw.stepinfoid)
WHERE 1=1
";
        sql = string.Format(sql, jObject["containerid"].ToString());

        if (jObject["workflowid"] != null)
        {
            sql += string.Format(" AND ws.workflowid='{0}'", jObject["workflowid"].ToString());
        }

        if (jObject["teamname"] != null && jObject["teamname"].ToString() != "")
        {
            sql += string.Format(" AND t.teamname LIKE '%{0}%'", jObject["teamname"].ToString());
        }
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //导出
    void exportExcel(JObject jObject)
    {
        string sql = @"
SELECT tn.workflowname,to_char(tn.begindate,'yyyy/mm/dd') begindate,to_char(tn.finishdate,'yyyy/mm/dd') finishdate,e.fullname,
       mfg.mfgordername,tn.engineno,CASE WHEN te.attributevalue IS NULL THEN '未分解' ELSE '已分解' END isplan,wf.workflowid,
       CASE WHEN te.attributevalue IS NULL AND SYSDATE <= tn.finishdate THEN '未执行'
            WHEN te.attributevalue IS NULL AND SYSDATE > tn.finishdate THEN '已超期'
            WHEN te.attributevalue IS NOT NULL AND wf.status = 2 THEN '已回收'
            WHEN te.attributevalue IS NOT NULL AND wf.status = 1 THEN '执行中' END status,
       ws.workflowstepname,s.description,t.teamname,CASE WHEN csw.createdate IS NOT NULL THEN '已报工' ELSE '未报工' END isDone
FROM technicalnoticeinfo tn
LEFT JOIN employee e ON e.employeeid = tn.createemployeeid
LEFT JOIN 
(
     SELECT u.attributevalue,NVL(ep.enginecontainerid,ep.containerid) containerid
     FROM enginepartplan ep
     LEFT JOIN Userattribute u ON u.parentid = ep.mfgorderid AND u.userattributename='发动机'
     WHERE ep.type = 3
) te ON te.attributevalue = tn.engineno
LEFT JOIN
(
     SELECT u.attributevalue,mfg.mfgordername,mfg.mfgorderid
     FROM enginepartplan ep
     LEFT JOIN mfgorder mfg ON mfg.mfgorderid = ep.mfgorderid
     LEFT JOIN Userattribute u ON u.parentid = ep.mfgorderid AND u.userattributename='发动机'
     GROUP BY u.attributevalue,mfg.mfgordername,mfg.mfgorderid
) mfg ON mfg.attributevalue = tn.engineno
LEFT JOIN workflowbase wb ON wb.workflowname = tn.workflowname
LEFT JOIN workflow wf ON wf.workflowbaseid = wb.workflowbaseid 
LEFT JOIN Workflowstep ws ON ws.workflowid = wf.workflowid
LEFT JOIN team t ON t.teamid = ws.teamid
LEFT JOIN stepinfo s ON s.workflowstepid = ws.workflowstepid
LEFT JOIN stepinfobase sb ON s.stepinfobaseid = sb.stepinfobaseid
LEFT JOIN containerstepworkreport csw ON csw.containerid = te.containerid AND csw.isuse = 0 AND NVL(ws.workflowstepid,s.stepinfoid) = NVL(csw.workflowstepid,csw.stepinfoid)
WHERE 1=1
";
        //计通单号
        if (jObject["workflowname"] != null && jObject["workflowname"].ToString() != "")
        {
            sql += string.Format(" AND tn.workflowname LIKE '%{0}%' ", jObject["workflowname"].ToString());
        }

        //发动机号
        if (jObject["engineno"] != null && jObject["engineno"].ToString() != "")
        {
            sql += string.Format(" AND tn.engineno = '{0}' ", jObject["engineno"].ToString());
        }

        //订单号
        if (jObject["mfgordername"] != null && jObject["mfgordername"].ToString() != "")
        {
            sql += string.Format(" AND mfg.mfgordername = '{0}' ", jObject["mfgordername"].ToString());
        }

        //开始日期
        if (jObject["startdate"] != null && jObject["startdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["startdate"].ToString());
            if (arr.Count >= 2)
            {
                sql += string.Format(" AND tn.begindate >= to_date('{0}','yyyy-MM-dd')", arr[0].ToString());
                sql += string.Format(" AND tn.begindate <= to_date('{0}','yyyy-MM-dd')", arr[1].ToString());
            }
        }

        //结束日期
        if (jObject["enddate"] != null && jObject["enddate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["enddate"].ToString());
            if (arr.Count >= 2)
            {
                sql += string.Format(" AND tn.finishdate >= to_date('{0}','yyyy-MM-dd')", arr[0].ToString());
                sql += string.Format(" AND tn.finishdate <= to_date('{0}','yyyy-MM-dd')", arr[1].ToString());
            }
        }

        //编制人
        if (jObject["creater"] != null && jObject["creater"].ToString() != "")
        {
            sql += string.Format(" AND e.fullname LIKE '%{0}%' ", jObject["creater"].ToString());
        }

        //编制人
        if (jObject["teamname"] != null && jObject["teamname"].ToString() != "")
        {
            sql += string.Format(" AND t.teamname LIKE '%{0}%' ", jObject["teamname"].ToString());
        }

        //状态
        if (jObject["status"] != null && jObject["status"].ToString() != "")
        {
            string status = jObject["status"].ToString();
            if (status == "未执行")
            {
                sql += " AND te.attributevalue IS NULL AND SYSDATE <= tn.finishdate";
            }
            if (status == "执行中")
            {
                sql += " AND te.attributevalue IS NOT NULL AND wf.status = 1";
            }
            if (status == "已回收")
            {
                sql += " AND te.attributevalue IS NOT NULL AND wf.status = 2";
            }
            if (status == "已超期")
            {
                sql += " AND te.attributevalue IS NULL AND SYSDATE > tn.finishdate";
            }
        }

        DataTable dt = dal.GetDataTable(sql);
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        dt.Columns.Remove("workflowid");
        dt.Columns["workflowname"].Caption = "计通单号";
        dt.Columns["begindate"].Caption = "开始日期";
        dt.Columns["finishdate"].Caption = "结束日期";
        dt.Columns["fullname"].Caption = "编制人";
        dt.Columns["mfgordername"].Caption = "订单号";
        dt.Columns["engineno"].Caption = "发动机号";
        dt.Columns["isplan"].Caption = "是否已分解";
        dt.Columns["status"].Caption = "状态";
        dt.Columns["workflowstepname"].Caption = "工序";
        dt.Columns["description"].Caption = "工步";
        dt.Columns["teamname"].Caption = "要求执行小组";
        dt.Columns["isDone"].Caption = "是否已报工";
        ExportHelper.ExportExcel(dt, jObject["factoryname"].ToString() + "技通单查询报表");
    }
}